package cn.zhku.user.dao;



import java.sql.SQLException;
import java.util.ArrayList;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.junit.Test;

import cn.itcast.jdbc.TxQueryRunner;
import cn.zhku.user.domain.Admin;
import cn.zhku.user.domain.User;
import cn.zhku.user.service.UserException;

public class UserDao {
	private QueryRunner qr = new TxQueryRunner();
	
	
	public User findByUserName(String userName)  {
		try{
			String sql ="select * from user where userName=?";	
			return qr.query(sql, new BeanHandler<User>(User.class), userName);
		}catch(SQLException e){
			throw new RuntimeException(e);
		}
	}
	

	public User findByEmail(String email) {
		// TODO Auto-generated method stub
		return null;
	}

	
	public void addUser(User user) {
		try {
			String sql = "insert into user (userName,userPass,age,sex,email) values(?,?,?,?,?)";
			Object[] params = {user.getUserName(),user.getUserPass(),
					user.getAge(),user.getSex(),user.getEmail()};
			qr.update(sql,params);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		
	}
	
	public ArrayList<User> findAll() {
			try {
				String sql = "select * from user";
				return (ArrayList<User>) qr.query(sql, new BeanListHandler<User>(User.class));
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
	}
	
	public void update(User user) throws UserException {
			try {
				String sql = "update user set userName=?,userPass=?,age=?,sex=?,email=? where userId = ?";
				Object[] params = {user.getUserName(),user.getUserPass(),
						user.getAge(),user.getSex(),user.getEmail(),user.getUserId()};
				qr.update(sql,params);
			} catch (SQLException e) {
				throw new  UserException("修改失败");
			}	
		}
	
	public void delete(int userId) throws UserException {
			
			try {
				String sql = "delete from user where userId = ?";
				qr.update(sql,userId);
			} catch (SQLException e) {
				throw new  UserException("删除失败");
			}
	
	}
	public Admin AdminFindByName(String Adminname) {
		try{
			String sql ="select * from admin where name=?";	
			return qr.query(sql, new BeanHandler<Admin>(Admin.class), Adminname);
		}catch(SQLException e){
			throw new RuntimeException(e);
		}
	}
	
	
}
